<template>
  <div>
    <el-card class="projectContainer">
      <div class="menuItems">
        <div class="p_item" :class="selectOp === 'projectMgr' ? 'selected' : ''">
          <div @click="slectOp('projectMgr')" class="pName">项目管理</div>
        </div>
        <div class="p_item" :class="selectOp === 'pluginMgr' ? 'selected' : ''">
          <div @click="slectOp('pluginMgr')" class="pName">插件管理</div>
        </div>
      </div>
    </el-card>
    <div class="configContent">
      <div class="baseConfig">
        <!-- 项目管理 -->
        <el-card v-if="selectOp == 'projectMgr'">
          <el-button type="primary" @click="projectAddBtn">新增</el-button>
          <el-table :data="projectData" style="width: 100%">
            <el-table-column prop="name" label="名字" />
            <el-table-column prop="excel_path" label="excel路径" width="100" />
            <el-table-column prop="table_prefix" label="表前缀" />
            <el-table-column prop="table_suffix" label="表后缀" />
            <el-table-column fixed="right" label="操作">
              <template #default="scope">
                <el-button link type="primary" size="small" @click="pEdit(scope.row)">
                  {{scope.row.name=="示例"?"查看":"修改"}}
                </el-button>
                <el-button v-if="scope.row.name!='示例'" link type="primary" size="small" @click="pDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
            <template #empty>
              <div>暂无项目数据</div>
            </template>
          </el-table>
        </el-card>
      </div>
    </div>
  </div>
  <!-- 项目修改弹窗 -->
  <el-dialog v-model="projectDialg" :title="projectDialgTitle" width="1200">
    <div class="projectEditRegion">
      <div class="projectEditLeft">
        <el-input :disabled="editProjectData.name=='示例'" class="item" v-model="editProjectData.name" style="max-width: 100%" placeholder="请输入项目名">
          <template #prepend>项目名：</template>
        </el-input>
        <el-input :disabled="editProjectData.name=='示例'" class="item" v-model="editProjectData.excel_path" style="max-width: 100%" placeholder="请输入excel表格路径">
          <template #prepend>excel文件夹：</template>
        </el-input>
        <el-input :disabled="editProjectData.name=='示例'" class="item" v-model="editProjectData.enum_file_name" style="max-width: 100%"
          placeholder="请输入枚举定义文件名">
          <template #prepend>枚举定义文件名：</template>
        </el-input>
        <el-input :disabled="editProjectData.name=='示例'" class="item" v-model="editProjectData.table_prefix" style="max-width: 100%" placeholder="请输入表格前缀">
          <template #prepend>表格前缀：</template>
        </el-input>
        <el-input :disabled="editProjectData.name=='示例'" class="item" v-model="editProjectData.table_suffix" style="max-width: 100%" placeholder="请输入表格后缀">
          <template #prepend>表格后缀：</template>
        </el-input>
      </div>
      <div class="projectEidtRight">
        <el-button v-if="editProjectData.name!='示例'" type="primary" @click="addProjectGroup">新增分组</el-button>
        <el-table :data="editProjectData.groups" border
          style="width: 100%">
          <el-table-column type="expand">
            <template #default="props">
              <!-- <p>{{props.row.params}}</p> -->
              <p  v-for="(v,k) in props.row.params"><el-tag type="primary" size="small">{{k }}</el-tag>&nbsp;&nbsp;： {{ v }}</p>
            </template>
          </el-table-column>
          <el-table-column label="英文名" prop="enName" />
          <el-table-column label="中文名" prop="chName" />
          <el-table-column fixed="right" label="操作">
              <template #default="scope">
                <el-button v-if="editProjectData.name!='示例'" link type="primary" size="small" @click="editProjectGroup(scope.row)">
                  修改
                </el-button>
                <el-button v-if="editProjectData.name!='示例'" link type="primary" size="small" @click="deleteProjectGroup(scope.row)">删除</el-button>
              </template>
            </el-table-column>
        </el-table>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="projectDialg = false">取消</el-button>
        <el-button v-if="editProjectData.name!='示例'" type="primary" @click="saveProjectCfg"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>


  <!-- 项目分组-->
  <el-dialog v-model="projectGroupEditDialog" title="项目分组" width="700">
    <div class="groupContent">
      <el-input class="item" v-model="editProjectGroupData.chName" style="max-width: 100%" placeholder="请输入组中文名">
        <template #prepend>组中文名：</template>
      </el-input>
      <el-input class="item" v-model="editProjectGroupData.enName" style="max-width: 100%" placeholder="请输入组英文名">
        <template #prepend>组英文名：</template>
      </el-input>
      <hr>
      <div v-for="param in groupParams" class="paramItem">
        <div>{{ param.key }}</div>
        <div>：</div>
        <el-input class="item" disabled v-model="param.value" style="max-width: 100%">
        </el-input>
        <el-button @click="deleteGroupPram(param.key)" type="danger">删除</el-button>
      </div>
      <div v-show="addGroupParamShow" class="addGroupParamShow">
        <el-input class="item" v-model="addParam.key" placeholder="键"></el-input>
        <div>：</div>
        <el-input class="item" v-model="addParam.value" placeholder="值">
        </el-input>
        <el-button @click="saveGroupParam" type="danger">保存</el-button>
      </div>
      <el-button type="primary" @click="addGroupParamShow = true">增加参数</el-button>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="projectGroupEditDialog = false">取消</el-button>
        <el-button type="primary" @click="saveGroup"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from "element-plus";
import { onMounted, Reactive, reactive, Ref, ref, watch } from "vue";
import { reqProjectList, savePjtCfg } from "../../../api/config";
import { ProjectCfg } from "../../../api/config/type";
import { guid } from "../../../utils/tools";
let projectOpType = ref("add"); //edit,add
let projectDialg = ref(false);
let projectDialgTitle = ref("修改");

let projectGroupEditDialog = ref(false)
let addGroupParamShow = ref(false)

let selectOp = ref("projectMgr");

const slectOp = (op: string) => {
  selectOp.value = op;
};




//====================项目操作Start======================



let projectData:Ref<ProjectCfg[]> = ref([]);

let editProjectData = reactive({
  "name": "",
  "excel_path": "",
  "enum_file_name": "",
  "table_prefix": "",
  "table_suffix": "",
  "groups": [
    {
      "enName":"s",
      "chName":"服务端",
      "params":{
        "enum_file_suffix":".data"
      }
    }
  ] as any[]
})
let editProjectGroupData = reactive({
  "uid":"1000",
  "enName": "s",
  "chName": "服务端",
  "params": {
    "key": "value"
  } as any
})
let groupParams: Ref<{ key: string, value: any }[]> = ref([])
let addParam: Reactive<{ key: string, value: string }> = reactive({
  key: "",
  value: ""
})

let groupOpType = "add"//edit
let saveProjectCfg = async ()=>{

  projectDialg.value = false
  console.log(editProjectData)
    let r = await savePjtCfg(editProjectData)
    if(r.code==200){
          //请求项目列表
      reqProjectList().then(res=>{
        if(res.code === 200) {
          projectData.value = res.data as ProjectCfg[]
        } else {
          ElMessage.error(res.msg)
        }
      })
    }else{
      ElMessage.error("保存失败："+r.msg)
    }

}

let saveGroupParam = () => {
  if (!addParam.key || !addParam.value) {
    ElMessage.error('键或值不能为空！')
    return
  }
  editProjectGroupData.params[addParam.key] = addParam.value
  let found = groupParams.value.find(el => el.key === addParam.key)
  if (found) {
    found.value = addParam.value
  } else {
    groupParams.value.push({
      key: addParam.key,
      value: addParam.value
    })
  }

  addParam.key = ""
  addParam.value = ""
  addGroupParamShow.value = false
}

const deleteGroupPram = (key: string) => {
  let temp = {} as any
  let toDelete = null
  groupParams.value.forEach(p => {
    if (p.key === key) {
      toDelete = p;
      return
    }
    temp[p.key] = p.value
  })
  //TODO 页面不刷新？
  let index = groupParams.value.indexOf(toDelete as any)
  if (index != -1) {
    groupParams.value.splice(index, 1)
  }
  editProjectGroupData.params = temp
  console.log(editProjectGroupData.params);

}

const saveGroup = () => {

  if(groupOpType=='add'){
    let found = editProjectData.groups.find(g => (g as any).enName === editProjectGroupData.enName)
    if (found) {
      ElMessage.error('组名重复：' + editProjectGroupData.enName)
      return
    }

    let newGroup = {
      uid: guid(),
      enName: editProjectGroupData.enName,
      chName: editProjectGroupData.chName,
      params: editProjectGroupData.params,
    }
    editProjectData.groups.push(newGroup)

    editProjectGroupData.enName = ""
    editProjectGroupData.chName = ""
    editProjectGroupData.params = {}
    projectGroupEditDialog.value = false
    return
  }

  //修改
  let oldGroup = editProjectData.groups.find(g => (g as any).uid === editProjectGroupData.uid)
  if(!oldGroup){
    ElMessage.error("数据异常！请刷新页面重试！")
    return
  }
  oldGroup.enName = editProjectGroupData.enName
  oldGroup.chName = editProjectGroupData.chName
  oldGroup.params = editProjectGroupData.params

  editProjectGroupData.enName = ""
  editProjectGroupData.chName = ""
  editProjectGroupData.params = {}
  projectGroupEditDialog.value = false
}

let addProjectGroup = () => {
  projectGroupEditDialog.value = true
  groupOpType = "add"
  editProjectGroupData.enName = ""
  editProjectGroupData.chName = ""
  editProjectGroupData.params = {}
  groupParams.value = []
}
let editProjectGroup = (data:any) => {
  projectGroupEditDialog.value = true
    groupOpType = "edit"
  editProjectGroupData.enName = data.enName
  editProjectGroupData.chName = data.chName
  editProjectGroupData.params = {}

  groupParams.value = []
  if(data.params){
    for(let key in data.params){
      groupParams.value.push({
        key:key,
        value:data.params[key]
      })
    }
  }
}

let deleteProjectGroup = (data:any)=>{
    //修改
    let oldGroup = editProjectData.groups.find(g => (g as any).uid === data.uid)
  if(!oldGroup){
    ElMessage.error("数据异常！请刷新页面重试！")
    return
  }
  let index = editProjectData.groups.indexOf(oldGroup)
  editProjectData.groups.splice(index,1)
}

const projectAddBtn = () => {
  projectDialgTitle.value = "新增项目";
  projectDialg.value = true;
  projectOpType.value = "add";
  editProjectData.name = "";
  editProjectData.excel_path = "";
  editProjectData.enum_file_name = "";
  editProjectData.table_prefix = "";
  editProjectData.table_suffix = "";
  editProjectData.groups = [];
};

const pEdit = (project: any) => {
  console.log("项目编辑：" + project);
  projectDialgTitle.value = "修改项目";
  projectDialg.value = true;
  projectOpType.value = "edit";
  // nowAddProjectConfig.value = projectAddTemp.value
  editProjectData.name = project.name;
  editProjectData.excel_path = project.excel_path;
  editProjectData.enum_file_name = project.enum_file_name;
  editProjectData.table_prefix = project.table_prefix;
  editProjectData.table_suffix = project.table_suffix;
  editProjectData.groups = project.groups;
};
const pDelete = (p: any) => {
  console.log("项目删除：" + p);
  ElMessageBox.confirm(`确定要删除项目 ${p.name} 吗？`, "注意", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    //TODO 发送消息删除项目
  });
};
//====================项目操作End======================

onMounted(()=>{
  //请求项目列表
  reqProjectList().then(res=>{
    if(res.code === 200) {
      projectData.value = res.data as ProjectCfg[]
    } else {
      ElMessage.error(res.msg)
    }
  })
})
</script>

<style scoped lang="scss">
:deep(.projectContainer > .el-card__body) {
  padding: 0;
}

.projectContainer {
  position: fixed;
  width: 80px;
  height: 80vh;
  border-radius: 3px;
  margin-top: 8vh;
  padding: 0;

  .menuItems {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: start;
    align-items: center;

    .p_item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      margin: 5px 0;
      padding: 0 3px;
    }

    .pName,
    .pEidt,
    .pDelete {
      cursor: pointer;
    }

    .selected {
      color: $base_color;
    }
  }
}

.configContent {
  margin-left: 140px;
}

.groupContent {
  display: flex;
  flex-direction: column;

  .item {
    padding: 10px 0px;
  }

  .paramItem {
    display: flex;
    padding: 0 10px;
    align-items: center;
  }

  .addGroupParamShow {
    display: flex;
    flex-direction: row;
    align-items: center;
  }
}

.templateDialogInput {
  display: flex;
  margin-bottom: 10px;
  align-items: center;
}

.groupDetailTable {
  color: green;
}

.projectEditRegion {
  display: flex;
  height: 100%;
  width: 100%;
  min-height: 50vh;

  .projectEditLeft {
    border-right: 1px solid gray;
    height: 100%;
    width: 50%;
    padding: 10px;

    .item {
      margin-top: 10px;
    }
  }

  .projectEidtRight {
    flex: 1;
    height: 100%;
    width: 50%;
    padding: 10px;
  }
}
</style>
